package tw.edu.tku.im.maze.database;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import tw.edu.tku.im.maze.Packet;
import tw.edu.tku.im.maze.PacketParser;

public class Processor extends Thread {
   
   static List<PacketProcessor> processor;
   static {
      processor = new ArrayList<PacketProcessor>();
      processor.add(new RegisterProcessor());
      processor.add(new LoginProcessor());
      processor.add(new AddRoomProcessor());
      processor.add(new EnterRoomProcessor());
      processor.add(new LeaveRoomProcessor());
      processor.add(new ChangeTeamProcessor());      
      processor.add(new UpdateRoomProcessor());
      processor.add(new StartGameProcessor());
      processor.add(new RoomListProcessor());
      processor.add(new UpdateGameProcessor());
      processor.add(new MarkProcessor());
      processor.add(new EndGameProcessor());
      processor.add(new HeartBeatProcessor());
   }
         
   BufferedReader in ;
   PrintWriter out ;
   
   public Processor(Socket client) throws IOException{
      in = new BufferedReader(new InputStreamReader(client.getInputStream(),"UTF-8"));
      out = new PrintWriter(new OutputStreamWriter(client.getOutputStream(),"UTF-8"));
   }
   
   private String process(String str) {
      JSONObject jsonObj = new JSONObject(str);
//      String action = json.getString("action");
      Packet req = PacketParser.parsePacket(jsonObj);
//      System.out.println("getPacketName");
//      System.out.println(req.getPacketName());
      if(req==null) {
         return "Error Meessage!!";
      }
      for(int i=0; i<processor.size(); i++) {
         if(processor.get(i).acceptName().equals(req.getPacketName())) {
           return  processor.get(i).process(req).toJSONString();
         }
      }     
      return "Error Meessage!";
   }
   
   public void run() {
      try {
         String req = in.readLine();
         System.out.println("Server收到:"+req);
         String rep = process(req);
         out.println(rep);
         System.out.println("Server回覆:"+rep);
         out.flush();
         in.close();
         out.close();
      } catch (IOException e) {
         System.out.println("發生傳輸例外");
         e.printStackTrace();
      }
   }

}
